package activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.volley.VolleyError;
import com.qzhy.female.R;

import Constant.Constance;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import fragment.AllPostFragment;
import fragment.UserPostFragment;
import model.Fans_Result;
import model.Fans_status;
import model.FocusCircle_Result;
import model.FocusStatus;
import model.FocusUser_Result;
import model.FocusUser_status;
import model.HxStatus;
import model.Sign_status;
import utils.Bimp;
import utils.GsonUtils;
import utils.HTTPUtils;
import utils.SetUtils;
import volley.VolleyListener;

public class MineActivity extends BaseActivity implements OnClickListener {

	private ImageView mImgBack;
	private ImageView mImgUserIcon;
	private TextView mTvUserName;
	private String path;
	private Uri photoUri;
	private float dp;
	public List<Bitmap> bmp = new ArrayList<Bitmap>();
	public List<String> drr = new ArrayList<String>();
	private LinearLayout mLlFollowCircle;
	private LinearLayout mLlFollowUser;
	private LinearLayout mLlFans;
	private TextView mTvCircleNum;
	private TextView mTvAttentionNum;
	private TextView mTvFansNum;
	private int mFanId=0;
	private RelativeLayout mRtlPost;
	private RelativeLayout mRtlAllPost;
	private TextView mTvChat;
	 private SharedPreferences.Editor et;
	 private SharedPreferences sp;
	private TextView mTvFocusUser;
	private int userID;
	private boolean IsUserFocused;//ture 还没被关注  false 已经被关注
	private int mAttentionSize;
	private int mFanSize;
	private String UserFocused;
	private String UserNickName;
	private String HxUser;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mine);
		sp = getSharedPreferences(Constance.CHATS.SP_NAME, MODE_PRIVATE);
	    et = sp.edit();
	    GetIntent();
		InitFrament();
		InitUI();
		InitUserInfo();
		IsFocusUser();
	}

	private void GetIntent() {
		Intent intent = getIntent();
		userID = intent.getIntExtra(Constance.INTENT.USER_ID, 0);
	}

	private void IsFocusUser() {
		if(SetUtils.GetUserId(getApplicationContext())==userID){
			mTvFocusUser.setText("本人");
		}else {
			//Constance.URL.USER+"/"+SetUtils.GetUserId(getApplicationContext())+"/attention_user/"+userID
			HTTPUtils.get(getApplicationContext(),Constance.URL.USER+"/"+SetUtils.GetUserId(getApplicationContext())+"/attention_user/"+userID+"/isattention", new VolleyListener() {
				@Override
				public void onResponse(String arg0) {
					showToast(arg0.toString());
					model.Praise focusUser = GsonUtils.parseJSON(arg0,model.Praise.class);
					UserFocused=focusUser.getStatus();
					if(focusUser.getStatus().equals(Constance.STATUS_TYPE.ERROR)){
						mTvFocusUser.setText("已关注");
						IsUserFocused=false;
					}else {
						mTvFocusUser.setText("关注");
						IsUserFocused=true;
					}
				}
				
				@Override
				public void onErrorResponse(VolleyError arg0) {
					showToast(arg0.toString());
				}
			});
		}
	}


	private void InitFrament() {
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		ft.replace(R.id.frame, new UserPostFragment());
		ft.commit();
	}

	private void InitUserInfo() {
			HTTPUtils.get(getApplicationContext(), Constance.URL.USER+"/"+userID, new VolleyListener() {
				@Override
				public void onResponse(String arg0) {
					Sign_status userStatus = GsonUtils.parseJSON(arg0, Sign_status.class);
					UserNickName= userStatus.getResult().getNickname();
					mTvUserName.setText(UserNickName);
					if(userStatus.getResult().getProfileImg().startsWith("http")){
						utils.UILUtils.displayImage(userStatus.getResult().getProfileImg(), mImgUserIcon);
					}else {
						utils.UILUtils.displayImage(Constance.URL.IMG_BASE+userStatus.getResult().getProfileImg(), mImgUserIcon);
					}
				}
				@Override
				public void onErrorResponse(VolleyError arg0) {
					
				}
			});
			HTTPUtils.get(getApplicationContext(), Constance.URL.USER+"/"+userID+"/focus", new VolleyListener() {
				@Override
				public void onResponse(String arg0) {
//					Toast.makeText(getApplicationContext(), arg0.toString(),1).show();
					FocusStatus focus = GsonUtils.parseJSON(arg0, FocusStatus.class);
					if(focus.getStatus().equals("success")){
						FocusCircle_Result result = focus.getResult();
						mTvCircleNum.setText(""+result.getFocus().size());
					}
				}
				@Override
				public void onErrorResponse(VolleyError arg0) {
					
				}
			});
			HTTPUtils.get(getApplicationContext(), Constance.URL.USER+"/"+userID+"/attentions", new VolleyListener() {
				@Override
				public void onResponse(String arg0) {
					FocusUser_status focusUser_status = GsonUtils.parseJSON(arg0, FocusUser_status.class);
					if(focusUser_status.getStatus().equals("success")){
						FocusUser_Result result = focusUser_status.getResult();
						mAttentionSize = result.getAttentions().size();
						mTvAttentionNum.setText(""+mAttentionSize);
					}
				}
				@Override
				public void onErrorResponse(VolleyError arg0) {
					
				}
			});
			HTTPUtils.get(getApplicationContext(), Constance.URL.USER+"/"+userID+"/followers", new VolleyListener() {
				
				@Override
				public void onResponse(String arg0) {
					Fans_status fans_status = GsonUtils.parseJSON(arg0, Fans_status.class);
					if(fans_status.getStatus().equals("success")){
						mFanId = fans_status.getResult().getId();
						Fans_Result result = fans_status.getResult();
						mFanSize = result.getFollowers().size();
						mTvFansNum.setText(""+mFanSize);
					}
				}
				@Override
				public void onErrorResponse(VolleyError arg0) {
					
				}
			});
			
	}

	private void InitUI() {
		mImgBack = (ImageView) findViewById(R.id.img_backs);
		mImgBack.setOnClickListener(this);
		
		mImgUserIcon = (ImageView) findViewById(R.id.img_icon);
		mImgUserIcon.setOnClickListener(this);
		mTvUserName = (TextView) findViewById(R.id.tv_username);
		
		mLlFollowCircle = (LinearLayout) findViewById(R.id.ll_circle);
		mLlFollowUser = (LinearLayout) findViewById(R.id.ll_follow);
		mLlFans = (LinearLayout) findViewById(R.id.ll_fans);
		mLlFollowCircle.setOnClickListener(this);
		mLlFollowUser.setOnClickListener(this);
		mLlFans.setOnClickListener(this);
		
		mTvCircleNum = (TextView) findViewById(R.id.tv_circle_num);
		mTvAttentionNum = (TextView) findViewById(R.id.tv_attention_num);
		mTvFansNum = (TextView) findViewById(R.id.tv_fans_num);
		
		mRtlPost = (RelativeLayout) findViewById(R.id.rtl_post);
		mRtlAllPost = (RelativeLayout) findViewById(R.id.rtl_all_post);
		
		mTvChat = (TextView) findViewById(R.id.tv_chat);
		mTvChat.setOnClickListener(this);
		
		mRtlPost.setOnClickListener(this);
		mRtlAllPost.setOnClickListener(this);
		
		mTvFocusUser = (TextView) findViewById(R.id.tv_focus_user);
		mTvFocusUser.setOnClickListener(this);
		
		if(SetUtils.GetUserId(getApplicationContext())==userID){
			mTvChat.setVisibility(View.GONE);
			mTvFocusUser.setVisibility(View.GONE);
		}else {
			mTvChat.setVisibility(View.VISIBLE);
			mTvFocusUser.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_backs:
			Intent data = new Intent();
		    setResult(Constance.INTENT.UPDATE_HEADER, data);
			finish();
			break;
		case R.id.img_icon:
			UpdateIcon();
			break;
		case R.id.ll_circle:
			Intent intent = new Intent(this,FollowCircleActivity.class);
			intent.putExtra(Constance.INTENT.USER_ID,userID);
			startActivity(intent);
			break;
		case R.id.ll_follow:
			startActivity(new Intent(this,FollowUserActivity.class));
			break;
		case R.id.ll_fans:
			Intent intent2 = new Intent(this,MyFansActivity.class);
			intent2.putExtra(Constance.INTENT.USER_ID, userID);
			startActivity(intent2);
			break;
		case R.id.rtl_post:
			GetUserPost();
			break;
		case R.id.rtl_all_post:
			GetAllPost();
			break;
		case R.id.tv_chat:
			 getChatUser();
			
			break;
		case R.id.tv_focus_user:
			if(IsUserFocused){
				FocusUser();
			}else {
				CancleFocusUser();
			}
			break;
		default:
			break;
		}
	}
	private void getChatUser() {
		showLoadingDialog("开始私聊...");
		HTTPUtils.get(this, Constance.URL.USER+"/"+userID+"/easemob", new VolleyListener() {
			@Override
			public void onResponse(String arg0) {
				HxStatus hxStatus = GsonUtils.parseJSON(arg0, HxStatus.class);
				if(hxStatus.getStatus().equals(Constance.STATUS_TYPE.SUCCESS)){
					dismissLoadingDialog();
					Toast.makeText(getApplicationContext(), "用户环信用户:"+hxStatus.getResult().getEasemobName(), 1).show();
					Intent chat = new Intent(MineActivity.this, ChatActivity.class);
					chat.putExtra(Constance.CHATS.USERID, hxStatus.getResult().getEasemobName());
					chat.putExtra(Constance.CHATS.CHATTYPE, 1);//单聊
					chat.putExtra(Constance.INTENT.USER_NAME, UserNickName);//用户昵称
			        startActivity(chat);
				}
			}
			@Override
			public void onErrorResponse(VolleyError arg0) {
				showToast(arg0.toString());
			}
		});
	}
	private void CancleFocusUser() {//取消关注
		if(SetUtils.GetUserId(getApplicationContext())==userID){
			mTvFocusUser.setText("是我");
		}else {
			Map<String, String> params=new HashMap<String,String>();
			params.put("user_id",""+SetUtils.GetUserId(getApplicationContext()));
			params.put("attention_user_id",""+userID);
			HTTPUtils.post(getApplicationContext(), Constance.URL.UNATTENTION_USER, params, new VolleyListener() {
				@Override
				public void onResponse(String arg0) {
					showToast(arg0.toString());
					model.Praise focusUser = GsonUtils.parseJSON(arg0,model.Praise.class);
					if(focusUser.getStatus().equals(Constance.STATUS_TYPE.SUCCESS)){
						mTvFocusUser.setText("关注");
						IsUserFocused=true;
					}
					switch (UserFocused) {
					case Constance.STATUS_TYPE.SUCCESS:
						mTvFansNum.setText(""+(mFanSize));
						break;
					case Constance.STATUS_TYPE.ERROR:
						mTvFansNum.setText(""+(mFanSize-1));
						break;
					default:
						break;
					}
				}
				@Override
				public void onErrorResponse(VolleyError arg0) {
					showToast(arg0.toString());
				}
			});
		}
	}

	//关注用户
	private void FocusUser() {
		if(SetUtils.GetUserId(getApplicationContext())==userID){
			mTvFocusUser.setText("是我");
		}else {
			Map<String, String> params=new HashMap<String,String>();
			params.put("user_id",""+SetUtils.GetUserId(getApplicationContext()));
			params.put("attention_user_id",""+userID);
			HTTPUtils.post(getApplicationContext(), Constance.URL.ATTENTION_USER, params, new VolleyListener() {
				@Override
				public void onResponse(String arg0) {
					showToast(arg0.toString());
					model.Praise focusUser = GsonUtils.parseJSON(arg0,model.Praise.class);
					if(focusUser.getStatus().equals(Constance.STATUS_TYPE.SUCCESS)){
						mTvFocusUser.setText("已关注");
						IsUserFocused=false;
					}
					switch (UserFocused) {
					case Constance.STATUS_TYPE.SUCCESS:
						mTvFansNum.setText(""+(mFanSize+1));
						break;
					case Constance.STATUS_TYPE.ERROR:
						mTvFansNum.setText(""+(mFanSize));
						break;

					default:
						break;
					}
				}
				
				@Override
				public void onErrorResponse(VolleyError arg0) {
					showToast(arg0.toString());
				}
			});
		}
	}

	private void GetAllPost() {
		InitFrament();
	}

	private void GetUserPost() {
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		ft.replace(R.id.frame, new AllPostFragment());
		ft.commit();
	}

	private void UpdateIcon() {
		String sdcardState = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
			new PopupWindows(MineActivity.this);
		} else {
			Toast.makeText(getApplicationContext(), "sdcard已拔出，不能选择照片",
					Toast.LENGTH_SHORT).show();
		}
	}
	
	public class PopupWindows extends PopupWindow {
		public PopupWindows(Context mContext) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(view, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			/**
			 * 拍照
			 */
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Takephoto();
					dismiss();
				}
			});
			/**
			 * 从相册中选取
			 */
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent i = new Intent(
							// 相册
							Intent.ACTION_PICK,
							android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					startActivityForResult(i, Constance.PICTURE.RESULT_LOAD_IMAGE);
					dismiss();
				}
			});
			/**
			 * 取消
			 */
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
		protected void Takephoto() {
			try {
				Intent openCameraIntent = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);

				String sdcardState = Environment.getExternalStorageState();
				String sdcardPathDir = android.os.Environment
						.getExternalStorageDirectory().getPath() + "/tempImage/";
				File file = null;
				if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
					// 有sd卡，是否有myImage文件夹
					File fileDir = new File(sdcardPathDir);
					if (!fileDir.exists()) {
						fileDir.mkdirs();
					}
					// 是否有headImg文件
					file = new File(sdcardPathDir + System.currentTimeMillis()
							+ ".JPEG");
				}
				if (file != null) {
					path = file.getPath();
					photoUri = Uri.fromFile(file);
					openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

					startActivityForResult(openCameraIntent, Constance.PICTURE.TAKE_PICTURE);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case Constance.PICTURE.TAKE_PICTURE:
			if (drr.size() < 2 && resultCode == -1) {// 拍照
				startPhotoZoom(photoUri);
			}
			break;
		case Constance.PICTURE.RESULT_LOAD_IMAGE:
			if (resultCode == RESULT_OK && null != data) {// 相册返回
				Uri uri = data.getData();
				if (uri != null) {
					startPhotoZoom(uri);
				}
			}
			break;
		case Constance.PICTURE.CUT_PHOTO_REQUEST_CODE:
			if (resultCode == RESULT_OK && null != data) {// 裁剪返回
				Bitmap bitmap = Bimp.getLoacalBitmap(drr.get(drr.size() - 1));
//				Mim.bitmap.add(bitmap);
				bitmap = Bimp.createFramedPhoto(480, 480, bitmap,
						(int) (dp * 1.6f));
//				bmp.add(bitmap);
				mImgUserIcon.setImageBitmap(bitmap);
				sendImg(bitmap);
			}
			break;
		case Constance.PICTURE.SELECTIMG_SEARCH:
			if (resultCode == RESULT_OK && null != data) {
				String text = "#" + data.getStringExtra("topic") + "#";
				Toast.makeText(getApplicationContext(), "selectimg_search", Toast.LENGTH_SHORT).show();
			}
			break;
		}
	}
	
	private void startPhotoZoom(Uri uri) {
		try {
			// 获取系统时间 然后将裁剪后的图片保存至指定的文件夹
			SimpleDateFormat sDateFormat = new SimpleDateFormat(
					"yyyyMMddhhmmss");
			String address = sDateFormat.format(new java.util.Date());
			if (!utils.FileUtils.isFileExist("")) {
				utils.FileUtils.createSDDir("");

			}
			drr.add(utils.FileUtils.SDPATH + address + ".JPEG");
			Uri imageUri = Uri.parse("file:///sdcard/formats/" + address
					+ ".JPEG");

			final Intent intent = new Intent("com.android.camera.action.CROP");

			// 照片URL地址
			intent.setDataAndType(uri, "image/*");

			intent.putExtra("crop", "false");
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("outputX", 480);
			intent.putExtra("outputY", 480);
			// 输出路径
			intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
			// 输出格式
			intent.putExtra("outputFormat",
					Bitmap.CompressFormat.JPEG.toString());
			// 不启用人脸识别
			intent.putExtra("noFaceDetection", false);
			intent.putExtra("return-data", false);
			startActivityForResult(intent, Constance.PICTURE.CUT_PHOTO_REQUEST_CODE);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 上传图片到服务端
	 */
	    private void sendImg(Bitmap bitmap){
	    	showLoadingDialog("正在更新");
	        ByteArrayOutputStream stream = new ByteArrayOutputStream();
	        bitmap.compress(CompressFormat.PNG, 60, stream);
	        byte[] byteArray = stream.toByteArray();
	        String img = new String(Base64.encodeToString(byteArray, Base64.DEFAULT)); 
	        Map<String, String> params=new HashMap<String, String>();
	        params.put("photo", img);
	        HTTPUtils.put(getApplicationContext(),Constance.URL.USER+"/"+SetUtils.GetUserId(getApplicationContext()), params, new VolleyListener() {
	            @Override
	            public void onResponse(String arg0) {
	            	if(arg0!=null){
	            		dismissLoadingDialog();
	            		Log.i("传头像信息", arg0.toString());
	            		Sign_status sign_status = GsonUtils.parseJSON(arg0, Sign_status.class);
	            		if(sign_status.getStatus().equals(Constance.STATUS_TYPE.SUCCESS)){
	            			showToast("更新成功");
	            			if(sign_status.getResult().getProfileImg().startsWith("http")){
	            				SetUtils.saveUserIcon(getApplicationContext(), sign_status.getResult().getProfileImg());
	            			}else {
	            				SetUtils.saveUserIcon(getApplicationContext(), Constance.URL.IMG_BASE+sign_status.getResult().getProfileImg());
	            			}
	            		}
	            	}
	            }
	            @Override
	            public void onErrorResponse(VolleyError arg0) {
	            	Toast.makeText(getApplicationContext(), "volleyerror", 1).show();
	            }
	        });
	    }
}
